import Vue from 'vue'
import VueRouter from 'vue-router'


import MyLogin from '@/components/MyLogin'


Vue.use(VueRouter)

const routes = [
  //一级路由(登录和首页)
  { path: '/', redirect: '/home' },
  { path: '/login', component: MyLogin },
  {
    path: '/home', component: () => import('@/components/MyHome'),
    children: [
      { path: 'users', component: () => import('@/components/menus/MyUsers') },
      { path: 'rights', component: () => import('@/components/menus/MyRights') },
      { path: 'orders', component: () => import('@/components/menus/MyOrders') },
      { path: 'goods', component: () => import('@/components/menus/MyGoods') },
      { path: 'settings', component: () => import('@/components/menus/MySettings') },
      // 用户详情也展示到了首页的内容区域,所以也是二级路由
      { path: 'userDetail/:id', component: () => import('@/components/user/MyUserDetail') },
    ]
  }
]

const router = new VueRouter({
  routes
})
//全局前置导航守卫
router.beforeEach((to, from, next) => {
  // to.path  //表示即将要访问的那个地址
  // from  //从哪里来
  // next()---表示放行  next(false)--不允许通过
  // next('/login')---强行跳转到login
  if (to.path === '/login') {
    next()//访问登录页,允许访问,直接放行
  } else {
    //访问的不是登录页面,需要判断有没有token
    if (localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
